<template>
    <div ref="chartContainer" class="container"> 
    </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { fishWeightApi } from "@/api/fishWeight";

const props = defineProps<{
  activeButton: number
}>();

const chartContainer = ref<HTMLDivElement | null>(null);
let myChart: echarts.ECharts | null = null;

// 获取识别地点统计数据
const getLocationStatisticsData = async () => {
  try {
    const response = await fishWeightApi.getLocationStatistics();
    const data = response.data;
    
    // 处理数据，提取地址和对应的统计数量
    const addresses: string[] = [];
    const counts: number[] = [];
    
    // 统计每个地址出现的次数
    const addressCountMap: { [key: string]: number } = {};
    data.forEach((item: any) => {
      const address = item.address || '未知地址';
      addressCountMap[address] = (addressCountMap[address] || 0) + 1;
    });
    
    // 转换为数组格式并排序，限制最多显示5个
    Object.entries(addressCountMap)
      .sort((a, b) => (b[1] as number) - (a[1] as number)) // 按数量降序排序
      .slice(0, 5) // 只取前5个数据
      .forEach(([address, count]) => {
        addresses.push(address);
        counts.push(count);
      });
    
    // 更新图表
    updateChart(addresses, counts);
  } catch (error) {
    console.error('获取识别地点统计数据失败:', error);
  }
};

// 更新图表
const updateChart = (addresses: string[], counts: number[]) => {
  if (!myChart) return;
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: addresses,
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          fontSize: 18,
          color: 'whitesmoke'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          fontSize: 18,
          color: 'whitesmoke'
        }
      }
    ],
    series: [
      {
        name: '识别次数',
        type: 'bar',
        barWidth: '60%',
        data: counts
      }
    ]
  };
  
  myChart.setOption(option, true);
};

onMounted(() => { 
  // 使用 ref 替代 getElementById
  if (chartContainer.value) {
    myChart = echarts.init(chartContainer.value);
    
    // 初始加载数据
    getLocationStatisticsData();
  }
  
  // 监听activeButton变化，当切换到识别地点时重新加载数据
  watch(() => props.activeButton, (newVal) => {
    if (newVal === 0) {
      getLocationStatisticsData();
    }
  });
});

// 组件卸载时销毁图表
onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
});
</script>

<style scoped>
.container{
    width: 100%;
    height: 100%;
}
</style>